﻿/*
	Copyright (C) 2019 Zongming Liu <1849059316@qq.com>

	This program is free software; you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation; either version 2 of the License, or
	(at your option) any later version.
	
	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.
	
	You should have received a copy of the GNU General Public License along
	with this program; if not, write to the Free Software Foundation, Inc.,
	51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/


#include<algorithm>
#include "RenderQueue.h"
#include "RenderCommand.h"
#include "../base/Debuger.h"

#define DEFAULT_ZERO_SIZE 500
#define DEFAULT_RRECEDENCE_SIZE 200
#define DEFAULT_LOW_SIZE 200

namespace SkyEngine2d
{
	
	RenderQueue::RenderQueue()
		:NonCopyable() 
	{
		m_queues[GLOABL_ZORDER_ZERO].reserve(DEFAULT_ZERO_SIZE);
		m_queues[GLOABL_ZORDER_PRECEDENCE].reserve(DEFAULT_RRECEDENCE_SIZE);
		m_queues[GLOABL_ZORDER_LOW].reserve(DEFAULT_LOW_SIZE);
	}
	
	RenderQueue::~RenderQueue()
	{
	
	}
	
	void RenderQueue::pushRenderCommand(RenderCommandPtr cmd)
	{
		int order = (int)cmd->getGlobalOrder();
		if (order == 0)
		{
			m_queues[GLOABL_ZORDER_ZERO].push_back(cmd);
		}
		else if (order > 0)
		{
			m_queues[GLOABL_ZORDER_PRECEDENCE].push_back(cmd);
		}
		else
		{
			m_queues[GLOABL_ZORDER_LOW].push_back(cmd);
		}
	
		return;
	}
	
	void RenderQueue::sort()
	{
		static auto order_func = [](const RenderCommandPtr & cmd_1, const RenderCommandPtr & cmd_2) ->bool
		{
			return cmd_1->getGlobalOrder() > cmd_2->getGlobalOrder();
		};
		if (m_queues[GLOABL_ZORDER_LOW].size()> 2)
		{
			std::sort(m_queues[GLOABL_ZORDER_LOW].begin(), m_queues[GLOABL_ZORDER_LOW].end(),order_func);
		}
	
		if (m_queues[GLOABL_ZORDER_PRECEDENCE].size()>2)
		{
			std::sort(m_queues[GLOABL_ZORDER_PRECEDENCE].begin(), m_queues[GLOABL_ZORDER_PRECEDENCE].end(), order_func);
		}
	}
	
	void RenderQueue::clear()
	{
		for (auto & v:m_queues)
		{
			v.clear();
		}
	}
	
	void RenderQueue::saveRenderState()
	{
		//TODO
	}
	
	void RenderQueue::restoreRenderState()
	{
		//TODO
	}
	
	
	const std::vector<RenderQueue::RenderCommandPtr>& RenderQueue::getRenderQueue(Type queue_type)
	{
		DebugerAssert(queue_type < QUEUE_COUNT, "意料之外的渲染队列的类型");
		return m_queues[queue_type];
	}
	
	
}
